﻿
using AutoMapper;
using MediatR;
using ProductionManagement.Application.Command.ScrapsCommand;
using ProductionManagement.Domain.ProductionDomain;
using ProductionManagement.Infrstructre.lnterface;
using SqlSugar;

namespace ProductionManagement.Application.CommandHandler.ScrapsCommandHandler
{
    public class AddScrapsCommandHandler : IRequestHandler<AddScrapsCommand, int>
    {
        IProductionWasteRepository pwRep;
        IProduceScrapsProductsRepository pspRep;
        ISqlSugarClient db;
        IMapper mapper;

        public AddScrapsCommandHandler(IProductionWasteRepository pwRep, ISqlSugarClient db, IMapper mapper, IProduceScrapsProductsRepository pspRep)
        {
            this.pwRep = pwRep;
            this.db = db;
            this.mapper = mapper;
            this.pspRep = pspRep;
        }

        public async Task<int> Handle(AddScrapsCommand request, CancellationToken cancellationToken)
        {
            // 开始事务
            db.Ado.BeginTran();

            try
            {
                //添加废料
                var feed = mapper.Map<ProductionWaste>(request.addDto);
                feed.ProductionWasteNumber = Guid.NewGuid().ToString().Replace("-","");
                var taskToAdd = await pwRep.AddAsync(feed);


                //添加废料产品
                foreach (var item in request.addDto.ProductWasteList)
                {
                    ProduceScrapsProducts detail = new ProduceScrapsProducts
                    {
                        ProductId = item.ProductId,
                        ProductionWasteNumber = feed.ProductionWasteNumber,
                        Office_Id = item.Office_Id,
                        User_Id = item.User_Id,
                        PScrapsNumber=item.PScrapsNumber,
                        AddName=item.AddName,
                        AddTime=item.AddTime,

                    };
                    await pspRep.AddAsync(detail);
                }

                // 提交事务
                db.Ado.CommitTran();

                return 1;  // 返回最终的结果
            }
            catch (Exception)
            {
                // 回滚事务
                db.Ado.RollbackTran();
                throw;
            }
        }

    }
}
